package org.luxor.commons.security.component;

import org.luxor.commons.core.exception.BaseException;
import org.luxor.commons.core.web.RestStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.web.HttpRequestMethodNotSupportedException;


/**
 * 异常处理,重写oauth 默认实现
 *
 * @author lengleng @date 2019/2/1
 */
public class Oauth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws BaseException {

        // Try to extract a SpringSecurityException from the stacktrace
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);

        Exception ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(new BaseException(RestStatus.UNAUTHORIZED, ase));
        }

        ase = (InsufficientScopeException) throwableAnalyzer.getFirstThrowableOfType(InsufficientScopeException.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(new BaseException(RestStatus.UNAUTHORIZED, ase));
        }

        ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(new BaseException(RestStatus.FORBIDDEN, ase));
        }

        ase = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(new BaseException(RestStatus.INVALID_GRANT, ase));
        }

        ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(new BaseException(RestStatus.METHOD_NOT_ALLOWED, ase));
        }

        ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(new BaseException(RestStatus.TOKEN_INVALID, ase));
        }

        return handleOAuth2Exception(new BaseException(RestStatus.SERVER_ERROR, e));
    }

    private ResponseEntity<OAuth2Exception> handleOAuth2Exception(BaseException e) {
        OAuth2Exception cause = (OAuth2Exception) e.getCause();

        Integer status = (Integer) e.asMap(true).get("code");
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CACHE_CONTROL, "no-store");
        headers.set(HttpHeaders.PRAGMA, "no-cache");
        if (status == RestStatus.UNAUTHORIZED.code()) {
            headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, cause.getSummary()));
        }

        // 客户端异常直接返回客户端,不然无法解析
        if (e.getCause() instanceof ClientAuthenticationException) {
            return new ResponseEntity(e, headers, HttpStatus.valueOf(status));
        }
        return new ResponseEntity<>(new OAuth2Exception(cause.getMessage(), cause), headers,
                HttpStatus.valueOf(status));
    }

}
